package sites.aeg.tags;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import core.HtmlMapper;
import core.ISiteMapper;

public class DetailPageAegTag implements ISiteMapper {

    @HtmlMapper(xpath = "//h1[contains(@class,'customHeaderV2')]")
    private String type;

    @HtmlMapper(xpath = "//img[@class = 'productImage']/@src")
    private String productImage;

    public String getProductImage() {
        return productImage;
    }

    public void setProductImage(String productImage) {
        this.productImage = productImage;
    }

    /**
     * @return the type
     */
    public String getType() {
        return type;
    }

    /**
     * @param type
     *            the type to set
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @return the shortDescr
     */
    public String getShortDescr() {
        return shortDescr;
    }

    /**
     * @param shortDescr
     *            the shortDescr to set
     */
    public void setShortDescr(String shortDescr) {
        this.shortDescr = shortDescr;
    }

    /**
     * @return the kleur
     */
    public String getKleur() {
        return kleur;
    }

    /**
     * @param kleur
     *            the kleur to set
     */
    public void setKleur(String kleur) {
        this.kleur = kleur;
    }

    /**
     * @return the specifications
     */
    public List<String> getSpecifications() {
        return specifications;
    }

    /**
     * @param specifications
     *            the specifications to set
     */
    public void setSpecifications(List<String> specifications) {
        this.specifications = specifications;
    }

    public void addSpecifications(String specifications) {
        this.specifications.add(specifications);
    }

    @HtmlMapper(xpath = "//p[contains(@id,'ShortDescription')]")
    private String shortDescr;
    @HtmlMapper(xpath = "//span[@id='productColor']")
    private String kleur;

    @HtmlMapper(xpath = "//a[contains(@id,'SubCategor')]/@href")
    private List<String> productLinks = new ArrayList<String>();

    @HtmlMapper(xpath = "//a[contains(@id,'ProductImageLink')]/@href")
    private List<String> productDetailLinks = new ArrayList<String>();

    @HtmlMapper(xpath = "//div[@id='featureWrapper']/div/div[@class='clear']")
    private List<FeatureAegTag> features = new ArrayList<FeatureAegTag>();

    @HtmlMapper(xpath = "//div[@id='specificationWrapper']//td")
    private List<String> specifications = new ArrayList<String>();

    private String category;

    /**
     * @return the category
     */
    public String getCategory() {
        return category;
    }

    /**
     * @param category
     *            the category to set
     */
    public void setCategory(String category) {
        this.category = category;
    }

    /**
     * @return the features
     */
    public List<FeatureAegTag> getFeatures() {
        return features;
    }

    /**
     * @param features
     *            the features to set
     */
    public void setFeatures(List<FeatureAegTag> features) {
        this.features = features;
    }

    public void addFeatures(FeatureAegTag features) {
        this.features.add(features);
    }

    /**
     * @return the productDetailLinks
     */
    public List<String> getProductDetailLinks() {
        return productDetailLinks;
    }

    /**
     * @param productDetailLinks
     *            the productDetailLinks to set
     */
    public void setProductDetailLinks(List<String> productDetailLinks) {
        this.productDetailLinks = productDetailLinks;
    }

    public void addProductDetailLinks(String productDetailLinks) {
        this.productDetailLinks.add(productDetailLinks);
    }

    /**
     * @return the productLinks
     */
    public List<String> getProductLinks() {
        return productLinks;
    }

    /**
     * @param productLinks
     *            the productLinks to set
     */
    public void setProductLinks(List<String> productLinks) {
        this.productLinks = productLinks;
    }

    public void addProductLinks(String productLink) {
        this.productLinks.add(productLink);
    }

    public String getSpecsXml() {
        StringBuilder sb = new StringBuilder();

        boolean type = true;
        sb.append("<specs>");
        for (String s : getSpecifications()) {
            if (type) {
                sb.append("<item type=\"" + s + "\">");
            }
            else {
                sb.append(s + "</item>");
            }
            type = !type;
        }
        sb.append("</specs>");
        return sb.toString();
    }

    public String getFeaturesXml() {
        StringBuilder sb = new StringBuilder();
        sb.append("<functions>");
        for (FeatureAegTag f : getFeatures()) {
            sb.append("<item type=\"" + f.getTitle() + "\">");
            sb.append(f.getDescr() + "</item>");
        }
        sb.append("</functions>");
        return sb.toString();
    }

    public String getDataSheetXml() {
        return getFeaturesXml() + getSpecsXml();
    }

    public void generateScript(Writer out) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO TMP_AEG_PRODUCTS(category, type, descr, color, specs) values (");
        sb.append("\"" + getCategory() + "\",\"" + getType() + "\",\"" + getShortDescr() + "\",\"" + getKleur() + "\",\'" + getDataSheetXml() + "\');");
        String img = "http://www.aeg-electrolux.it/products/XMLLARGERIMAGE/PSAARE100P000104.png";

        try {
            out.write(sb.toString());
            writeDataToFile(img, "test.png");
        }
        catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void writeDataToFile(String url, String filename) throws Exception {

        URL u = new URL(url);
        URLConnection uc = u.openConnection();

        String contentType = uc.getContentType();
        int contentLength = uc.getContentLength();
        if (contentType.startsWith("text/") || contentLength == -1) {
            throw new IOException("This is not a binary file.");
        }
        InputStream raw = uc.getInputStream();
        InputStream in = new BufferedInputStream(raw);
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1) break;
            offset += bytesRead;
        }
        in.close();

        if (offset != contentLength) {
            throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
        }

        FileOutputStream out = new FileOutputStream(filename);
        out.write(data);
        out.flush();
        out.close();
    }

}
